//
//  NetWorking.m
//  RadioUrl
//
//  Created by ios on 16/4/24.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "NetWorking.h"
#import <AFNetworking.h>
#import "RadioModel.h"
@implementation NetWorking
+(void)searchWithJsonUrl:(NSString *)url success:(void(^)(RadioModel *radioModel))successBlock failure: (void(^)(NSError *error))failureBlock{
  
    NSString *radioSource = [NSString stringWithFormat:@"http://www.ximalaya.com/tracks/%@.json",url];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSLog(@"%@",radioSource);
    [manager GET:radioSource parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = (NSDictionary *)responseObject;
//        NSLog(@"%@",responseObject);
        RadioModel *radioModel = [[RadioModel alloc]init];
        NSString *title = dict[@"title"];
        title = [NetWorking replaceUnicode:title];
        radioModel.radioTitle = title;
        radioModel.radioTimeLength = dict[@"duration"];
//        radioModel.radioImage = dict[@"cover_url"];
        radioModel.radioPath = dict[@"play_path"];
        NSLog(@"%@_----%@------%@",radioModel.radioTitle,radioModel.radioImage,radioModel.radioPath);
        //将当前的电台的model存在单例中
        successBlock(radioModel);
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failureBlock(error);
    }];
}

//Unicode解码radioTitle
+ (NSString *)replaceUnicode:(NSString *)unicodeStr {
    
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    
    //NSLog(@"Output = %@", returnStr);
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

@end
